/**
 * 版权所有：厦门市巨龙信息科技有限公司
 * Copyright 2024 Xiamen Dragoninfo Eng. Co. Ltd.
 * All right reserved.
 */
package com.github.alfred.tool.impl;

import com.github.alfred.exception.BizException;
import com.github.alfred.tool.DistributedLocker;
import org.redisson.api.RLock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

/**
 * 类说明
 *
 * @author chengh
 * @date 2024/1/19 15:58
 */
public abstract class RedissonDistributedLockerProcessor {
    private static final Logger log = LoggerFactory.getLogger(RedissonDistributedLockerProcessor.class);

    private final DistributedLocker distributedLocker;

    protected RedissonDistributedLockerProcessor(DistributedLocker distributedLocker) {
        this.distributedLocker = distributedLocker;
    }

    /**
     * 基于分布式锁业务处理
     *
     * @param map   参数
     * @param clazz 返回值类型
     * @param <T>   泛型
     * @return T
     */
    public abstract <T> T processBusiness(Map<String, Object> map, Class<T> clazz);

    public <T> T lock(String key, Map<String, Object> map, Class<T> clazz) {
        RLock lock = distributedLocker.tryLock(key);
        try {
            return processBusiness(map, clazz);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new BizException("DistributedLockerException", e);
        } finally {
            distributedLocker.unlock(lock);
        }
    }

}
